import React from "react";
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import * as productActions from '../store/actions/product.action'
import * as cartActions from '../store/actions/cart.action'

class Product extends React.Component {

  constructor(props) {
    super()
  }

  componentDidMount() {
    const { GET_PRODUCT }  = this.props
    GET_PRODUCT()
    // this.props['SET_PRODUCT']()
  }

  render() {
    const { products, ADD_PRODUCT_TO_CART } = this.props 
    return (
      <section className="container content-section">
        <h2 className="section-header">商品列表</h2>
        <div className="shop-items">
          { products.map(item => {
            return <div className="shop-item" key={item.id}>
              <img className="shop-item-image" src={`http://localhost:3005${item.thumbnail}`} alt={item.title} />
              <span className="shop-item-title">{ item.title }</span>
              <div className="shop-item-details">
                <span className="shop-item-price">￥{item.price}</span>
                <button onClick={() => { ADD_PRODUCT_TO_CART(item.id) }} className="btn btn-primary shop-item-button" type="button">加入购物车</button>
              </div>
            </div>
          }) }
        </div>
      </section>
    )
  }
}

const mapStateToProps = state => ({
  products: state.products,
  carts: state.carts
})

const mapDispatchToProps = dispatch => ({
  ...bindActionCreators(productActions, dispatch),
  ...bindActionCreators(cartActions, dispatch)
})

export default connect(mapStateToProps, mapDispatchToProps)(Product)